<?php
/**
 * 这里是登录操作
 * 
 * @author jerry
 * @version $Id$
 * @package model
 *
 */

class Login_model extends Model 
{
	/**
	 * 解析函数
	 *
	 */
	function __construct()
	{
		parent::__construct();
	}
	
	/**
	 * 用户登录
	 *
	 * @param string $user
	 * @param string $pass
	 */
	function login($user,$pass)
	{
		global $sys_info;
		
		
		$this->where("UserName",$user);
		$this->where("PassWord",md5($pass));
		
		$user_info = $this->getDataInfo('admin');

		if($user_info)
		{
			
			$this->regSession($user_info);
			
			return true;
		}
		else 
		{
			return false;
		}
	}
	
	/**
	 * 注册Session
	 *
	 */
	function regSession($user_info)
	{
		$this->clearSession();
		
		$this->where('IP',$this->in_var['IP_ADDRESS']);
		$this->dataDel('system_session');
		
		$_SESSION['yanghuan_sys_info']['Sid'] = md5(time() . $this->in_var['IP_ADDRESS'] . rand(1111,9999));
		$_SESSION['yanghuan_sys_info']['UserID'] = $user_info['UserID'];
		$_SESSION['yanghuan_sys_info']['UserName'] = $user_info['UserName'];
		$_SESSION['yanghuan_sys_info']['IP'] = $this->in_var['IP_ADDRESS'];
		$_SESSION['yanghuan_sys_info']['LastActivity'] = time();
		
		session_register('yanghuan_sys_info');
		
		$this->addData('Sid',$_SESSION['yanghuan_sys_info']['sid']);
		$this->addData('UserID',$user_info['UserID']);
		$this->addData('UserName',$user_info['UserName']);
		$this->addData('IP',$this->in_var['IP_ADDRESS']);
		$this->addData('LastActivity',time());
		
		$this->dataInsert('system_session');
		

	}
	
	/**
	 * 更新Session
	 *
	 */
	function updateSession()
	{
		$this->addData('LastActivity',time());
		$this->where('Sid', $_SESSION['yanghuan_sys_info']['Sid']);
		$this->dataUpdate('system_session');
		$_SESSION['yanghuan_sys_info']['LastActivity'] = time();
	}
	
	/**
	 * 清楚过期Sesssion
	 *
	 */
	function clearSession()
	{
		$now_time = time() - $this->sys_conf_var['session']['online_hold'];
		
		$this->where('LastActivity',$now_time,'<=');
		$this->dataDel('system_session');
	}
	
	/**
	 * 删除Session
	 *
	 */
	function delSession()
	{
		$this->clearSession();
		
		$this->where('Sid',$_SESSION['yanghuan_sys_info']['sid']);
		$this->dataDel('system_session');
		
		session_destroy($_SESSION['yanghuan_sys_info']);
		unset($_SESSION['yanghuan_sys_info']);
	}
	
	/**
	 * 验证Session
	 *
	 */
	function verify()
	{
		if(!$_SESSION['yanghuan_sys_info']['sid'])
		{
			goto('index.php','js','top');
		}
		
		$this->clearSession();

		$this->where('IP',$this->in_var['IP_ADDRESS']);
		$this->where('Sid',$_SESSION['yanghuan_sys_info']['sid']);
		
		$session_info = $this->getDataInfo('system_session','Sid');

		if($session_info)
		{
			$this->updateSession();
		}
		else
		{
			$this->delSession();

			goto('index.php?c=login&d=login&msg=' . urlencode('登录已过期,请重新登陆'),'js','top');
		}

		$this->tpl->assign("SessionInfo", $_SESSION['yanghuan_sys_info']);
	}
	
}